import { StatusBar } from 'expo-status-bar';
import { StyleSheet, Text, View, Image, TouchableOpacity, ScrollView, Dimensions, Animated } from 'react-native';
import AntDesign from 'react-native-vector-icons/AntDesign';
import { LinearGradient } from 'expo-linear-gradient';
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { useNavigation } from '@react-navigation/native';
import { StackNavigationProp } from '@react-navigation/stack';

// 定义导航类型
type RootStackParamList = {
  Individual: undefined;
  // 添加其他页面路由类型...
};

type NavigationProp = StackNavigationProp<RootStackParamList, 'Individual'>;

// 定义用户数据接口
interface UserData {
  name: string;
  grade: string;
}

// 定义组件Props接口
interface FadingRotatingTextProps {}

const { width: screenWidth } = Dimensions.get('window');

// 定义getLearningFeatureIcon函数的返回值类型
const getLearningFeatureIcon = (index: number): string => {
  switch (index) {
    case 0: return 'clockcircleo';    // 最近上新
    case 1: return 'book';            // 知识背记
    case 2: return 'rocket1';         // 专项突破
    case 3: return 'user';            // 人文素养
    default: return 'questioncircle';
  }
};

// 定义FadingRotatingText组件的返回值类型为JSX.Element
const FadingRotatingText: React.FC<FadingRotatingTextProps> = () => {
  const [currentIndex, setCurrentIndex] = useState<number>(0);
  const fadeAnim = new Animated.Value(1);
  const translateYAnim = new Animated.Value(0);

  const texts: string[] = [
    "✨ 定制专属心意，赠好友VIP >>",
    "🎁 新人特惠，首月仅3.2元！ >>",
    "📚 今日精讲视频已上新，快来瞅瞅 >>"
  ];

  useEffect(() => {
    const interval = setInterval(() => {
      Animated.sequence([
        Animated.parallel([
          Animated.timing(fadeAnim, {
            toValue: 0,
            duration: 500,
            useNativeDriver: true,
          }),
          Animated.timing(translateYAnim, {
            toValue: -20,
            duration: 500,
            useNativeDriver: true,
          })
        ]),
        Animated.timing(translateYAnim, {
          toValue: 20,
          duration: 0,
          useNativeDriver: true,
        }),
        Animated.parallel([
          Animated.timing(fadeAnim, {
            toValue: 1,
            duration: 500,
            useNativeDriver: true,
          }),
          Animated.timing(translateYAnim, {
            toValue: 0,
            duration: 500,
            useNativeDriver: true,
          })
        ])
      ]).start(() => {
        setCurrentIndex((prev) => (prev + 1) % texts.length);
      });
    }, 3000);

    return () => clearInterval(interval);
  }, []);

  return (
    <Animated.Text
      style={[
        styles.vipGift,
        {
          opacity: fadeAnim,
          transform: [{ translateY: translateYAnim }],
        }
      ]}
    >
      {texts[currentIndex]}
    </Animated.Text>
  );
};

// 定义App组件的返回值类型为JSX.Element
const App: React.FC = () => {
  const navigation = useNavigation<NavigationProp>();
  // 定义userData的类型
  const [userData, setUserData] = useState<UserData>({
    name: '',
    grade: ''
  });

  useEffect(() => {
    const fetchData = async (): Promise<void> => {
      try {
        const response = await axios.get('http://172.20.10.3:3000/cyw/pi');
        console.log('API Response:', response.data);

        if (response.data.code === 200 && response.data.pilist.length > 0) {
          const user = response.data.pilist[0];
          setUserData({
            name: user.name,
            grade: user.grade
          });
        }
      } catch (error) {
        console.error('API Error:', error);
        setUserData({
          name: '加载失败',
          grade: '请检查网络'
        });
      }
    };

    fetchData();
  }, []);
  return (
    <View style={styles.container}>
      <LinearGradient
        colors={['#2399FD', '#2399FD', '#F7F9FA', '#F7F9FA', '#F7F9FA', '#F7F9FA']}
        style={styles.backgroundGradient}
      />

      {/* Fixed Daily Check-in Button */}
      <TouchableOpacity style={styles.fixedCheckInButton}>
        <Text style={styles.checkInText}>每日签到</Text>
      </TouchableOpacity>

      <ScrollView style={styles.scrollView} contentContainerStyle={styles.scrollContent}>
        {/* Header Section */}
        <View style={styles.header}>
          {/* Profile Section */}
          <TouchableOpacity
            style={styles.profileSection}
            onPress={() => navigation.navigate('Individual')} // 使用 navigation.navigate 进行页面跳转
          >
            <Image
              style={styles.avatar}
              source={require('../../../assets/hellokitty.jpg')}
            />
            <View style={styles.userInfo}>
              <View style={styles.userNameRow}>
                <Text style={styles.username}>{userData.name}</Text>
                <View style={styles.levelBadge}>
                  <Text style={styles.levelText}>激活等级</Text>
                </View>
              </View>
              <View style={styles.userDetails}>
                <Text style={styles.achievement}>1成就</Text>
              </View>
              <View style={styles.userDetails}>
                <Text style={styles.userSchool}>填写学校 {userData.grade}</Text>
              </View>
            </View>
          </TouchableOpacity>

          {/* Swipeable Membership Cards */}
          <ScrollView
            horizontal
            pagingEnabled
            showsHorizontalScrollIndicator={false}
            style={styles.cardsContainer}
          >
            {/* VIP Card - First card (default visible) */}
            <LinearGradient
              colors={['#FFE6AD', '#FEC664']} // 从左到右的橙色渐变
              start={{ x: 0, y: 0 }}          // 从左开始
              end={{ x: 1, y: 0 }}            // 到右结束
              style={[styles.card, styles.vipCard]}
            >
              <View style={styles.vipInfo}>
                <Text style={styles.vipText}>VIP会员</Text>
                <Text style={styles.vipDescription}>开通会员立即享多重特权</Text>
                <FadingRotatingText />
              </View>
              <TouchableOpacity style={styles.vipButton}>
                <Text style={styles.vipButtonText}>首月3.9元</Text>
              </TouchableOpacity>
            </LinearGradient>

            {/* Learning Member Card with Gradient Background */}
            <LinearGradient
              colors={['#A4F9DE', '#37E3AE']} // 青绿色渐变
              start={{ x: 0, y: 0 }}         // 从左开始
              end={{ x: 1, y: 0 }}           // 到右结束
              style={[styles.card, styles.learningCard]}
            >
              <View style={styles.learningCardHeader}>
                <Text style={styles.learningCardTitle}>听学会员</Text>
                <TouchableOpacity style={styles.learningCardButton}>
                  <Text style={styles.learningCardButtonText}>立即开通</Text>
                </TouchableOpacity>
              </View>
              <View style={styles.featuresGrid}>
                {['最近上新', '知识背记', '专项突破', '人文素养'].map((feature, index) => (
                  <View key={feature} style={styles.featureItem}>
                    <View style={styles.iconContainer}>
                      <AntDesign
                        name={getLearningFeatureIcon(index)}
                        size={24}
                        color="#09DC8F"  // 改为白色图标
                        style={styles.featureIcon}
                      />
                    </View>
                    <Text style={styles.featureText}>{feature}</Text>
                  </View>
                ))}
              </View>
            </LinearGradient>
          </ScrollView>

          {/* Tools Section */}
          <View style={styles.section}>
            <Text style={styles.sectionTitle}>作业工具</Text>
            <View style={styles.toolsGrid}>
              {['搜索记录', '练习记录', '我的收藏', '错题本'].map((tool, index) => (
                <TouchableOpacity key={tool} style={styles.toolItem}>
                  <View style={styles.toolIcon}>
                    <AntDesign
                      name={getIconName(index)}
                      size={24}
                      color="#007AFF"
                    />
                  </View>
                  <Text style={styles.toolText}>{tool}</Text>
                </TouchableOpacity>
              ))}
            </View>
          </View>

          {/* Store Section */}
          <View style={styles.section}>
            <View style={styles.sectionHeader}>
              <Text style={styles.sectionTitle}>商城</Text>
              <Text style={styles.sectionSubtitle}>官方商城 售后无忧</Text>
            </View>
            <View style={styles.toolsGrid}>
              {['学习笔', '学习机', '单词卡', '喵喵机'].map((item, index) => (
                <TouchableOpacity key={item} style={styles.toolItem}>
                  <View style={styles.toolIcon}>
                    <AntDesign
                      name={getStoreIconName(index)}
                      size={24}
                      color="#FF9500"
                    />
                  </View>
                  <Text style={styles.toolText}>{item}</Text>
                </TouchableOpacity>
              ))}
            </View>
          </View>

          {/* Account Section */}
          <View style={styles.section}>
            <TouchableOpacity style={styles.accountListItem}>
              <Text style={styles.listItemText}>我的订单</Text>
              <Text style={styles.listItemRight}>商城订单 ›</Text>
            </TouchableOpacity>
            <TouchableOpacity style={styles.accountListItem}>
              <Text style={styles.listItemText}>学分兑换</Text>
              <Text style={styles.listItemRight}>›</Text>
            </TouchableOpacity>
            <TouchableOpacity style={styles.accountListItem}>
              <Text style={styles.listItemText}>会员购买记录</Text>
              <Text style={styles.listItemRight}>VIP、SVIP、听学 ›</Text>
            </TouchableOpacity>
            <TouchableOpacity style={styles.accountListItem}>
              <Text style={styles.listItemText}>我的卡券</Text>
              <Text style={styles.listItemRight}>优惠券、礼品卡 ›</Text>
            </TouchableOpacity>
            <TouchableOpacity style={styles.accountListItem}>
              <Text style={styles.listItemText}>学币&余额</Text>
              <Text style={styles.listItemRight}>›</Text>
            </TouchableOpacity>
            <TouchableOpacity style={styles.accountListItem}>
              <Text style={styles.listItemText}>礼豆商城</Text>
              <Text style={styles.listItemRight}>›</Text>
            </TouchableOpacity>
            <TouchableOpacity style={styles.accountListItem}>
              <Text style={styles.listItemText}>客服中心</Text>
              <Text style={styles.listItemRight}>设置 ›</Text>
            </TouchableOpacity>
          </View>
        </View>
      </ScrollView>

      {/* Bottom Navigation */}
      {/* <View style={styles.bottomNav}>
                {['首页', '资料库', 'VIP', '光速写作', '我'].map((item) => (
                    <TouchableOpacity key={item} style={styles.navItem}>
                        <Text style={styles.navText}>{item}</Text>
                    </TouchableOpacity>
                ))}
            </View> */}
      <StatusBar style="auto" />
    </View>
  );
};

// Icon mapping functions
const getIconName = (index: number): string => {
  switch (index) {
    case 0: return 'search1';
    case 1: return 'clockcircle';
    case 2: return 'star';
    case 3: return 'closecircle';
    default: return 'questioncircle';
  }
};

const getStoreIconName = (index: number): string => {
  switch (index) {
    case 0: return 'edit';
    case 1: return 'laptop';
    case 2: return 'book';
    case 3: return 'printer';
    default: return 'questioncircle';
  }
};

// Styles
const styles = StyleSheet.create({
  container: {
      flex: 1,
  },
  backgroundGradient: {
      position: 'absolute',
      left: 0,
      right: 0,
      top: 0,
      bottom: 0,
  },
  scrollView: {
      flex: 1,
  },
  scrollContent: {
      paddingTop: 50,
  },
  fixedCheckInButton: {
      position: 'absolute',
      left: 19,
      top: 30,
      backgroundColor: '#FFF0E6',
      paddingHorizontal: 12,
      paddingVertical: 6,
      borderRadius: 15,
      zIndex: 100,
  },
  checkInText: {
      color: '#FF6B00',
      fontSize: 14,
  },
  header: {
      padding: 16,
      paddingBottom: 20,
  },
  profileSection: {
      flexDirection: 'row',
      alignItems: 'center',
      marginBottom: 30,
      marginTop: 20,
  },
  avatar: {
      width: 100,
      height: 100,
      borderRadius: 50,
      backgroundColor: '#eee',
      marginLeft: 10,
  },
  userInfo: {
      marginLeft: 15,
      flex: 1,
  },
  userNameRow: {
      flexDirection: 'row',
      alignItems: 'center',
  },
  username: {
      fontSize: 25,
      fontWeight: 'bold',
      color: '#333',
  },
  levelBadge: {
      backgroundColor: '#FFF0E6',
      borderRadius: 4,
      paddingHorizontal: 6,
      paddingVertical: 2,
      marginLeft: 10,
  },
  levelText: {
      fontSize: 12,
      color: '#FF6B00',
  },
  userDetails: {
      flexDirection: 'row',
      marginTop: 6,
  },
  achievement: {
      fontSize: 17,
      color: '#666',
      marginRight: 15,
  },
  userSchool: {
      fontSize: 17,
      color: '#666',
  },
  cardsContainer: {
      height: 190,
      marginBottom: 20,
  },
  card: {
      width: screenWidth - 120,
      height: 180,
      marginHorizontal: 16,
      borderRadius: 12,
      padding: 16,
      shadowColor: '#000',
      shadowOffset: { width: 0, height: 2 },
      shadowOpacity: 0.1,
      shadowRadius: 4,
      elevation: 3,
  },
  vipCard: {
      flexDirection: 'row',
      justifyContent: 'space-between',
      alignItems: 'center',
      marginHorizontal: 10,
  },
  vipInfo: {
      flex: 1,
  },
  vipText: {
      fontSize: 19,
      fontWeight: 'bold',
      color: '#9D5502',
      marginTop: 20,
  },
  vipDescription: {
      color: '#C06D05',
      marginTop: 20,
      fontSize: 15,
  },
  vipGift: {
      color: '#FF4500',
      fontSize: 14,
      fontWeight: '600',
      backgroundColor: 'rgba(255,255,255,0.6)',
      paddingHorizontal: 10,
      paddingVertical: 15,
      borderRadius: 15,
      overflow: 'hidden',
      marginTop: 25,
      textShadowColor: 'rgba(0,0,0,0.1)',
      textShadowOffset: { width: 0.5, height: 0.5 },
      textShadowRadius: 1,
  },
  vipButton: {
      backgroundColor: '#FF6B00',
      paddingVertical: 8,
      paddingHorizontal: 15,
      borderRadius: 20,
      marginTop: -100,
  },
  vipButtonText: {
      color: 'white',
      fontSize: 14,
      fontWeight: '500',
  },
  learningCard: {
      marginHorizontal: 10,
  },
  learningCardHeader: {
      flexDirection: 'row',
      justifyContent: 'space-between',
      alignItems: 'center',
      marginBottom: 16,
  },
  learningCardTitle: {
      fontSize: 18,
      fontWeight: 'bold',
      color: '#016343',
      textShadowColor: 'rgba(0,0,0,0.2)',
      textShadowOffset: { width: 1, height: 1 },
      textShadowRadius: 2,
  },
  learningCardButton: {
      backgroundColor: '#007B49',
      paddingVertical: 8,
      paddingHorizontal: 15,
      borderRadius: 20,
      shadowColor: '#000',
      shadowOpacity: 0.2,
      shadowRadius: 3,
      elevation: 3,
  },
  learningCardButtonText: {
      color: '#FFF',
      fontSize: 14,
      fontWeight: '500',
  },
  featuresGrid: {
      flexDirection: 'row',
      justifyContent: 'space-between',
      alignItems: 'center',
      width: '100%',
      paddingHorizontal: 10,
  },
  featureItem: {
      alignItems: 'center',
      justifyContent: 'center',
  },
  iconContainer: {
      backgroundColor: 'rgb(255, 255, 255)',
      borderRadius: 25,
      width: 50,
      height: 50,
      alignItems: 'center',
      justifyContent: 'center',
      marginBottom: 8,
      marginTop: 10,
  },
  featureIcon: {
      marginBottom: 4,
  },
  featureText: {
      fontSize: 14,
      color: '#016343',
      marginTop: 5,
      // fontWeight: '500',
      fontWeight: 'bold',
  },
  section: {
      backgroundColor: 'white',
      borderRadius: 12,
      padding: 16,
      marginBottom: 17,
      shadowColor: '#000',
      shadowOpacity: 0.05,
      shadowRadius: 3,
      elevation: 1,
      margin: 10,
  },
  sectionHeader: {
      flexDirection: 'row',
      justifyContent: 'space-between',
      alignItems: 'center',
      marginBottom: 16,
  },
  sectionTitle: {
      fontSize: 19,
      fontWeight: 'bold',
      color: '#333',
  },
  sectionSubtitle: {
      fontSize: 12,
      color: '#999',
  },
  toolsGrid: {
      flexDirection: 'row',
      flexWrap: 'wrap',
      justifyContent: 'space-between',
      marginTop: 25,
  },
  toolItem: {
      width: '25%',
      alignItems: 'center',
      marginBottom: 12,
  },
  toolIcon: {
      width: 54,
      height: 54,
      borderRadius: 27,
      backgroundColor: '#F7F7F7',
      justifyContent: 'center',
      alignItems: 'center',
      marginBottom: 8,
  },
  toolText: {
      fontSize: 15,
      color: '#666',
  },
  accountListItem: {
      height: 58,
      flexDirection: 'row',
      justifyContent: 'space-between',
      alignItems: 'center',
      paddingVertical: 12,
      borderBottomWidth: 1,
      borderBottomColor: '#f0f0f0',
  },
  listItemText: {
      fontSize: 15,
      color: '#333',
  },
  listItemRight: {
      color: '#999',
      fontSize: 14,
  },
  bottomNav: {
      flexDirection: 'row',
      justifyContent: 'space-around',
      alignItems: 'center',
      paddingVertical: 12,
      backgroundColor: 'white',
      borderTopWidth: StyleSheet.hairlineWidth,
      borderTopColor: '#eee',
  },
  navItem: {
      alignItems: 'center',
  },
  navText: {
      fontSize: 12,
      color: '#666',
  },
});
export default App;    